//
//  SubmitListenTestViewController.m
//  Learn
//
//  Created by 迟建国 on 2024/4/2.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "SubmitListenTestViewController.h"
#import "TestOptionTableViewCell.h"
#import "TestFinishViewController.h"
#import "HomeRequest.h"
#import "TextbookQuestionsModel.h"
#import "PlayManager.h"
#import "TestSubCellViewModel.h"
@interface SubmitListenTestViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSString *json;

@property (nonatomic, strong) NSMutableArray *showArray;

@end

@implementation SubmitListenTestViewController
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear: animated];
    [[PlayManager sharPlayManager] pause];
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.view.backgroundColor = rgba(245, 245, 245, 1);
    [self setUI];
    self.showArray = @[].mutableCopy;
    self.json = [self getAnswerScoreJson];
    
}
- (void)back
{
    [self popToViewControllerWithClassName:@"ChapterDetailViewController" animated:YES];
}
- (void)setUI {
    
    self.tableView=[[UITableView alloc]initWithFrame:CGRectMake(10,lTopBarHeight + 10, SCREEN_W - 20, SCREEN_H - lTopBarHeight - SafeAreaBottomHeight - 70) style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    if (@available(iOS 13.0, *)) {
        [self.tableView setAutomaticallyAdjustsScrollIndicatorInsets:NO];
    } else {
        // Fallback on earlier versions
    }
    if (@available(iOS 15.0, *)) {
        self.tableView.sectionHeaderTopPadding = 0;
    } else {
        // Fallback on earlier versions
    }
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    self.tableView.backgroundColor=[UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    self.tableView.layer.cornerRadius = 15;
    self.tableView.layer.masksToBounds = YES;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    [self.tableView registerNib:[UINib nibWithNibName:@"TestOptionTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"TestOptionTableViewCell"];
    
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_H - SafeAreaBottomHeight - 50, SCREEN_W, SafeAreaBottomHeight + 50)];
    bottomView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:bottomView];
    
    CAGradientLayer *gl = [CAGradientLayer layer];
    gl.frame = CGRectMake(10,2.5,lScreenWidth - 20,45);
    gl.startPoint = CGPointMake(1, 0.5);
    gl.endPoint = CGPointMake(0, 0.5);
    gl.colors = @[(__bridge id)[UIColor colorWithRed:41/255.0 green:241/255.0 blue:156/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:2/255.0 green:161/255.0 blue:249/255.0 alpha:1.0].CGColor];
    gl.locations = @[@(0), @(1.0f)];
    gl.cornerRadius = 22.5;
    gl.masksToBounds = YES;
    [bottomView.layer addSublayer:gl];
    
    
    UIButton *submitBtn = [UIButton new];
    submitBtn.frame =CGRectMake(10, 2.5, lScreenWidth - 20, 45);
    
    [submitBtn setTitle:@"交作业" forState:UIControlStateNormal];
    //[_confirmButton setTitleColor:rgba(181, 181, 181, 1) forState:UIControlStateNormal];
    [submitBtn setTitleColor:lWhiteColor forState:UIControlStateNormal];
    [submitBtn.titleLabel setFont:MFontWithSize(18)];
    [submitBtn addTarget:self action:@selector(submit) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:submitBtn];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self renderNavBarWithBackgroundImage:[UIImage imageWithColor:lClearColor] backgroundColor:lClearColor shadowColor:nil textAttributeDic:@{NSForegroundColorAttributeName:rgba(51, 51, 51, 1),NSFontAttributeName:MFontWithSize(18)} enableScrollEdgeAppearance:NO];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.showArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    HSItem *model = self.showArray[section];
    return model.viewModel.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HSItem *model = self.showArray[indexPath.section];
    TestSubCellViewModel *modelView = model.viewModel[indexPath.row];
    HSQuestion *testModel = modelView.question;
    CGFloat height = [self getTextHeightWithWidth:SCREEN_W - 40 Font:SFontWithSize(16) Text:testModel.trunk.body];
    if (testModel.trunk.attachments.count > 0) {
        HSValueAttachment *k= testModel.trunk.attachments[0];
        for (HSValueAttachment *att in testModel.trunk.attachments) {
            if (att.fileType == 2) {
                k = att;
            }
        }
        if (modelView.img) {
            height = height + modelView.img.size.height/modelView.img.size.width*(SCREEN_W - 20) + 10;
        }
        if (k.url.length != 0) {
            height = height + 38;
        }
    }
    
    
    if (testModel.recordUrl.length != 0) {
        height = height + 70;
    }
    return  height;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TestOptionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TestOptionTableViewCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"TestOptionTableViewCell" owner:self options:nil] lastObject];
    }
    HSItem *model = self.showArray[indexPath.section];
    TestSubCellViewModel *testModel = model.viewModel[indexPath.row];
    cell.resmain = self.model.resmain;
    cell.viewModel = testModel;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    HSItem *model = self.showArray[section];
    
    CGFloat height = [self getTextHeightWithWidth:lScreenWidth - 40 Font:MFontWithSize(14) Text:model.templateSettings.content] + 54 + 10 ;
    return height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    HSItem *model = self.showArray[section];
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,lScreenWidth,115)];
    
    UILabel *titleLab = [[UILabel alloc] init];
    titleLab.frame = CGRectMake(10,10,lScreenWidth - 40,CGFLOAT_MIN);
    [headerView addSubview:titleLab];
    titleLab.font = MFontWithSize(14);
    titleLab.numberOfLines = 0;
    titleLab.textColor = rgba(51, 51, 51, 1);
    titleLab.text = model.templateSettings.content;
    titleLab.textAlignment = NSTextAlignmentLeft;
    [titleLab sizeToFit];
    
    UIButton *reDobtn  = ({
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"重做该题" forState:UIControlStateNormal];
        button.titleLabel.font = MFontWithSize(14.f);
        [button setTitleColor:lWhiteColor forState:UIControlStateNormal];
        button;
    });
    [reDobtn setAllCorner:17];
    reDobtn.frame = CGRectMake(10, titleLab.bottom + 10, 94, 34);
    reDobtn.tag = section;
    [reDobtn addTarget:self action:@selector(reDobtnButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:reDobtn];
    headerView.height = reDobtn.bottom;
    reDobtn.backgroundColor = rgba(12, 183, 108, 1);
    return headerView;
}
- (double)getTextHeightWithWidth:(double)width Font:(UIFont *)font Text:(NSString *)text
{
    UILabel *titleLab = [[UILabel alloc] init];
    titleLab.frame = CGRectMake(10,10,width,CGFLOAT_MIN);
    titleLab.font = font;
    titleLab.numberOfLines = 0;
    titleLab.textColor = rgba(51, 51, 51, 1);
    titleLab.text = text;
    titleLab.textAlignment = NSTextAlignmentLeft;
    [titleLab sizeToFit];
    return titleLab.height;
}
- (void)reDobtnButtonClick:(UIButton *)btn
{
    if (self.blcok) {
        self.blcok(btn.tag);
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)submit {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    
    dic[@"source_id"] = self.model.resource.versionId;
    dic[@"question_type"] = @"1";
    dic[@"question_source_type"] = @"1";
    dic[@"use_time"] = @([PlayManager sharPlayManager].useTime);
    dic[@"answer_score_json"] = self.json;
    dic[@"total_score"] = @(self.model.resource.totalScore);
    dic[@"json"] = [self.model modelToJSONString];
    if (self.mission_id.length != 0) {
        dic[@"mission_id"] = self.mission_id;
    }
    
    [HomeRequest submitTingshuoworkWith:dic result:^(NSDictionary *data) {
        NSLog(@"%@",data);
        if (data) {
            [PlayManager sharPlayManager].useTime = 0;
            TestFinishViewController *vc = [[TestFinishViewController alloc] init];
            vc.data = data;
            [self.navigationController pushViewController:vc animated:YES];
        } else {
            //            [NSObject showHudTipStr:@"提交失败！"];
        }
    }];
}
- (NSString *)getAnswerScoreJson
{
    NSMutableArray *aArray = @[].mutableCopy;
    
    for (int i = 0;  i < self.model.resource.items.count;i++) {
        HSItem *item = self.model.resource.items[i];
        NSDictionary *dic = [item mj_keyValues].mutableCopy;
        HSItem *new = [HSItem mj_objectWithKeyValues:dic];
        NSMutableArray *array = @[].mutableCopy;
        for (HSQuestion *quest in item.questions) {
            [array addObject:quest];
            if (quest.children.count == 0) {
                [aArray addObject:quest];
            }else{
                [array addObjectsFromArray:[self getQuestionWithQuestion:quest]];
                [aArray addObjectsFromArray:[self getQuestionWithQuestion:quest]];
            }
        }
        
        NSMutableArray *array1 = @[].mutableCopy;
        for (int a = 0; a < array.count; a++) {
            
            HSQuestion *quest = array[a];
            TestSubCellViewModel *model = [TestSubCellViewModel new];
            model.question = quest;
            
            HSValueAttachment *k= quest.trunk.attachments[0];
            HSValueAttachment *attImg= [HSValueAttachment new];
            for (HSValueAttachment *att in quest.trunk.attachments) {
                if (att.fileType == 2) {
                    k = att;
                }
                if (att.fileType == 1){
                    attImg = att;
                   
                }
            }
            
                if (attImg.url.length > 0) {
                    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",self.model.resmain,attImg.url]] completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
                        model.img = image;
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self.tableView reloadData];
                        });
                    }];
                }
            
            dispatch_queue_t t = dispatch_queue_create("my", nil);
            dispatch_async(t, ^{
                if (!IsStrEmpty(k.url)) {
                    NSString *imUrl = [NSString stringWithFormat:@"%@%@",self.model.resmain,k.url];
                    model.audioTimeAll = [MethodTool getAudioMp3TimeWithUrl:imUrl];
                }
                if (!IsStrEmpty(quest.recordUrl)) {
                    NSString *imUrl2 = [NSString stringWithFormat:@"%@",quest.recordUrl];
                    model.myAudioTimeAll = [MethodTool getAudioMp3TimeWithUrl:imUrl2];
                }
                
                if (a + 1 == array.count&&i + 1 == self.model.resource.items.count) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.tableView reloadData];
                    });
                }
            });
            
            [array1 addObject:model];
            
        }
        
        
        new.viewModel = array1;
        [self.showArray addObject:new];
    }
    
    NSMutableArray *dicArray = @[].mutableCopy;
    for (HSQuestion *quest in aArray)
    {
        NSMutableDictionary *dic = @{}.mutableCopy;
        NSString *color = quest.questionRefSorce > 7? @"yellow":quest.questionRefSorce >= 5? @"red":@"green";
        [dic setObject:@(quest.questionRefSorce) forKey:@"score"];
        [dic setObject:color forKey:@"color"];
        if (quest.recordUrl) {
            [dic setObject:quest.recordUrl forKey:@"url"];
        }
        if (quest.versionId.length != 0) {
            [dic setObject:@{@"version_id":quest.versionId} forKey:@"questionid"];
        }
        [dicArray addObject:dic];
    }
    return [dicArray modelToJSONString];
}
-(NSMutableArray *)getQuestionWithQuestion:(HSQuestion *)question
{
    NSMutableArray *aArray = @[].mutableCopy;
    for (HSQuestion *quest in question.children) {
        [aArray addObject:quest];
    }
    return aArray;
}
@end
